//输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的。 
//
// 示例1： 
//
// 输入：1->2->4, 1->3->4
//输出：1->1->2->3->4->4 
//
// 限制： 
//
// 0 <= 链表长度 <= 1000 
//
// 注意：本题与主站 21 题相同：https://leetcode-cn.com/problems/merge-two-sorted-lists/ 
// Related Topics 分治算法 
// 👍 44 👎 0

package leetcode.editor.cn;

import common.bean.ListNode;
import common.util.MyUtil;

/**
 * Java：合并两个排序的链表
 *
 * @author changgui
 */
@SuppressWarnings("all")
public class P剑指_offer_25_HeBingLiangGePaiXuDeLianBiaoLcof {
    public static void main(String[] args) {
        Solution solution = new P剑指_offer_25_HeBingLiangGePaiXuDeLianBiaoLcof().new Solution();
        ListNode l1 = MyUtil.createNode(1, 2, 4);
        ListNode l2 = MyUtil.createNode(1, 3, 4);
        ListNode listNode = solution.mergeTwoLists(l1, l2);
        MyUtil.printListNode(listNode);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null) {
                return l2;
            }
            if (l2 == null) {
                return l1;
            }
            ListNode newHead = new ListNode(0);
            for (ListNode curr = newHead, l1c = l1, l2c = l2; l1c != null || l2c != null; curr = curr.next) {
                if (l1c == null) {
                    // l2全体放在末尾
                    curr.next = l2c;
                    break;
                } else if (l2c == null) {
                    // l1全体放在末尾
                    curr.next = l1c;
                    break;
                } else if (l1c.val <= l2c.val) {
                    curr.next = l1c;
                    l1c = l1c.next;
                } else {
                    curr.next = l2c;
                    l2c = l2c.next;
                }
            }
            return newHead.next;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}